/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.util.List;

import javax.inject.Inject;

import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Kind;
import ru.irenproject.store.Stash;

public final class QuestionItem extends AbstractThing {
  public enum ChangeEvent implements Event { INSTANCE }

  public static final int MAX_WEIGHT = 1000;

  public static QuestionItem create(Question question) {
    QuestionItem res = question.store().create(QuestionItem.class);
    res.prepare(question);
    return res;
  }

  public static void checkValidWeight(int weight) {
    TestCheck.input(weight >= 1);
    TestCheck.input(weight <= MAX_WEIGHT);
  }

  @Stash private TestProtos.QuestionItem.Builder $;
  private final ProtoRegistry fProtoRegistry;

  @Inject QuestionItem(ProtoRegistry protoRegistry) {
    fProtoRegistry = protoRegistry;
  }

  private void prepare(Question question) {
    $.setQuestion(question.id())
     .setWeight(1)
     .setEnabled(true)
     .setModifierList(store().create(ModifierList.class).id())
     .setQuestionKind(fProtoRegistry.getThingKind(question.getClass()).value());
  }

  public void setWeight(int weight) {
    checkValidWeight(weight);
    $.setWeight(weight);
    post(ChangeEvent.INSTANCE);
  }

  public int weight() {
    return $.getWeight();
  }

  public Question question() {
    return get($.getQuestion(), Question.class);
  }

  public boolean enabled() {
    return $.getEnabled();
  }

  public void setEnabled(boolean value) {
    if (enabled() != value) {
      $.setEnabled(value);
      post(ChangeEvent.INSTANCE);
    }
  }

  public ModifierList modifierList() {
    return get($.getModifierList(), ModifierList.class);
  }

  public Kind questionKind() {
    return Kind.get($.getQuestionKind());
  }

  public void addLabel(String label) {
    $.addLabel(label);
    post(ChangeEvent.INSTANCE);
  }

  public List<String> labelList() {
    return $.getLabelList();
  }

  public void clearLabels() {
    $.clearLabel();
    post(ChangeEvent.INSTANCE);
  }
}
